package com.jrh.web.member;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jrh.biz.user.UserService;
import com.jrh.common.exception.UserAlreadyExistsException;
import com.jrh.domain.entity.User;
import com.jrh.domain.entity.UserProfile;
import com.jrh.domain.user.LoginUserInfo;
import com.jrh.web.extend.session.SessionUtil;
import com.jrh.web.member.tools.UserAuthUtil;
import com.jrh.web.model.JrhWebConstant;

/**
 * 前台用户登录
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-26 下午8:01:44
 */
@Controller
public class MemberController {

    @Autowired
    private UserService         userService;

    private static final String PAGE_REGISTER   = "member/register";
    private static final String PAGE_LOGIN      = "member/login";
    private static final String FORGET_PASSWORD = "member/forgetpassword";
    private static final String PAGE_ME         = "user/me";

    /**
     * 注册首页
     * 
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/register")
    public String register(@ModelAttribute("userForm") UserForm userForm, ModelMap map, HttpServletRequest request,
                           HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            return "redirect:" + PAGE_ME;
        }
        return PAGE_REGISTER;
    }

    /**
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/register")
    public String doRegister(@Valid @ModelAttribute("userForm") UserForm userForm, BindingResult result, ModelMap map,
                             HttpServletRequest request, HttpServletResponse response) {
        if (!validPcCode(userForm.getPcode(), request)) {
            map.put("checkError", "验证码出错!");
            return PAGE_REGISTER;
        }
        if (!userForm.getPassword().equals(userForm.getVerifyPassword())) {
            result.addError(new ObjectError("verifyPassword", "两次输入的密码必须一致!"));
            return PAGE_REGISTER;
        }
        if (result.hasErrors()) {
            return PAGE_REGISTER;
        }

        User user = new User();
        user.setLoginId(userForm.getLoginId());
        user.setPassword(userForm.getPassword());
        user.setNickname(userForm.getNickname());
        user.setSite(User.JRH_SELF_USER_SITE);
        user.setUserType(User.USER_TYPE_BUYER);
        UserProfile userProfile = new UserProfile();
        userProfile.setSex(userForm.getSex());
        // userProfile.setQuestion(userForm.getQuestion());
        // userProfile.setAnswer(userForm.getAnswer());
        try {
            boolean isSuccess = userService.createUser(user, userProfile);
            if (isSuccess) {
                LoginUserInfo loginUserInfo = new LoginUserInfo();
                loginUserInfo.setLoginId(userForm.getLoginId());
                loginUserInfo.setSite(User.JRH_SELF_USER_SITE);
                loginUserInfo.setType(User.USER_TYPE_BUYER);
                loginUserInfo.setNickname(userForm.getNickname());
                UserAuthUtil.signIn(loginUserInfo, request, response);
                return "redirect:" + PAGE_ME;
            }
        } catch (UserAlreadyExistsException e) {
            if (UserAlreadyExistsException.ERROR_CODE_LOGINID.equals(e.getErrorCode())) {
                result.rejectValue("loginId", "user.loginId.repeat", "用户已经存在");
            }
            if (UserAlreadyExistsException.ERROR_CODE_NICKNAME.equals(e.getErrorCode())) {
                result.rejectValue("nickname", "user.nickname.repeat", "昵称已经存在");
            }
        }
        return PAGE_REGISTER;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/login")
    public String login(@ModelAttribute("userForm") LoginUserForm userForm, String rUrl, Model model,
                        HttpServletRequest request, HttpServletResponse response) {
        if (UserAuthUtil.isSignIn(request, response)) {
            rUrl = isUrlValid(rUrl) ? rUrl : PAGE_ME;
            return "redirect:" + rUrl;
        }
        model.addAttribute("redirectUrl", rUrl);
        return PAGE_LOGIN;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public String doLogin(@Valid @ModelAttribute("userForm") LoginUserForm userForm, BindingResult result,
                          String redirectUrl, Model model, HttpServletRequest request, HttpServletResponse response) {

        if (UserAuthUtil.isSignIn(request, response)) {
            redirectUrl = isUrlValid(redirectUrl) ? redirectUrl : PAGE_ME;
            return "redirect:" + redirectUrl;
        }
        User user = userService.checkLogin(userForm.getLoginId(), userForm.getPassword(), User.JRH_SELF_USER_SITE);
        if (user == null) {
            model.addAttribute("hasError", true);
            return PAGE_LOGIN;
        }

        LoginUserInfo loginUserInfo = new LoginUserInfo();
        loginUserInfo.setId(user.getId());
        loginUserInfo.setLoginId(user.getLoginId());
        loginUserInfo.setNickname(user.getNickname());
        loginUserInfo.setSite(user.getSite());
        loginUserInfo.setType(user.getUserType());
        UserAuthUtil.signIn(loginUserInfo, request, response);
        redirectUrl = isUrlValid(redirectUrl) ? redirectUrl : PAGE_ME;
        return "redirect:" + redirectUrl;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        UserAuthUtil.signOut(request, response);
        return "redirect:" + "/login";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/forgetpassword")
    public String forgetpassword(HttpServletRequest request, HttpServletResponse response) {
        return FORGET_PASSWORD;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/question")
    public String question(@RequestParam(value = "loginId", required = true) String loginId, Model model,
                           HttpServletRequest request, HttpServletResponse response) {
        UserProfile userProfile = userService.getUserProfileByLoginId(loginId);
        if (userProfile == null) {
            return "redirect:" + "/forgetpassword";
        }
        model.addAttribute("userProfile", userProfile);
        model.addAttribute("loginId", loginId);
        return "member/question";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/forgetpassword")
    public String doForgetpassword(@RequestParam(value = "loginId", required = true) String loginId,
                                   @RequestParam(value = "password", required = true) String password,
                                   @RequestParam(value = "answer", required = true) String answer, Model model,
                                   HttpServletRequest request, HttpServletResponse response) {
        boolean success = userService.forgetpassword(loginId, password, answer);
        if (success) {
            return "redirect:" + "/login";
        }
        return "error";
    }

    /**
     * @param redirectUrl
     * @return
     */
    private boolean isUrlValid(String redirectUrl) {
        boolean valid = StringUtils.isNotBlank(redirectUrl);
        if (valid) {
            if (redirectUrl.substring(0, JrhWebConstant.WEB_ROOT_DOMAIN.length()).equals(JrhWebConstant.WEB_ROOT_DOMAIN)) {
                return Boolean.TRUE;
            }
            // Pattern regex = Pattern.compile("^" + JrhWebConstant.WEB_ROOT_DOMAIN);
            // Matcher matcher = regex.matcher("redirectUrl");
            // if (matcher.find()) {
            // return Boolean.TRUE;
            // }
        }
        return Boolean.FALSE;
    }

    private boolean validPcCode(String pcCode, HttpServletRequest request) {
        String pcodeFromSession = SessionUtil.getSession(request, JrhWebConstant.SESSION_PCODE_KEY, String.class, false);
        if (StringUtils.isBlank(pcCode) || StringUtils.isBlank(pcodeFromSession)) {
            return false;
        }
        if (pcCode.equalsIgnoreCase(pcodeFromSession)) {
            return true;
        }
        return false;
    }
}
